#include "Effect.h"

Effect::Effect()
: m_program(0)
{
}

Effect::~Effect()
{
	/*
	foreach(EffectVariable var, m_effectVariables)
	{
		if(var.hasGuiControl)
		{
			delete var.guiControl.widget;
		}
	} */
}

void Effect::setName(const QString& name)
{
	m_name = name;
}

void Effect::setGLSLFilename(const QString& filename)
{
	m_glslFilename = filename;
}

void Effect::addVariable(const EffectVariable& var)
{
	m_variables.push_back(var);
}

void Effect::loadShader(const QGLContext* context)
{
	m_pixelShader = new QGLShader(QGLShader::Fragment);
	
	QString source = loadShaderSource();

	if(!m_pixelShader->compileSourceCode(source))
	{
		QMessageBox message;
		message.setText("Failed to compile shader.");
		message.setInformativeText("Log:\n" + m_pixelShader->log() + "\n\nSource:\n" + source);
		message.exec();
	}

	m_program = new QGLShaderProgram(context);
	m_program->addShader(m_pixelShader);

	if(!m_program->link())
	{
		qDebug("Failed to link program.");
		//qDebug((const char*)m_program->log().constData());

		QString log = m_program->log();

		if(log.isNull())
		{
			QMessageBox isNullMsg;
			isNullMsg.setText("Log is null!");
			isNullMsg.exec();
		}

		QMessageBox message;
		message.setText("Failed to link shader program.\nLog:\n" + log);
		message.exec();
	}

//	m_loaded = true;
}

QString Effect::loadShaderSource()
{
	QFile file(m_glslFilename);
	if(!file.open(QFile::ReadOnly | QFile::Text))
	{
		QString error = file.errorString();

		QMessageBox message;
		message.setText("Failed to open effect file (\'" + m_glslFilename + "\').\nError: " + error);
		message.exec();
	}

	QString source;

	QTextStream stream(&file);
	while(!stream.atEnd())
	{
		source += stream.readLine() + "\n";
	}

	return source;
}

void Effect::activate(const QGLContext* glContext)
{
	loadShader(glContext);
	m_program->bind();
}

void Effect::deactivate()
{
	if(m_program)
		delete m_program;
}
